package com.kevinxiaoge.ruoli.exception;

import com.kevinxiaoge.ruoli.bean.ErrorReponse;
import com.kevinxiaoge.ruoli.controller.EmployeeController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author chengyuanyuan
 */
@ControllerAdvice(assignableTypes = {EmployeeController.class})
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public ResponseEntity<?> handleAppException(BaseException ex, HttpServletRequest request) {
        ErrorReponse errorReponse = new ErrorReponse(ex,request.getRequestURI());
        return new ResponseEntity<>(errorReponse,new HttpHeaders(),ex.getError().getStatus());
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorReponse> handleResourceNotFoundException(ResourceNotFoundException ex,HttpServletRequest request){
        ErrorReponse errorReponse = new ErrorReponse(ex,request.getRequestURI());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorReponse);
    }
}
